package cc.mrbird.system.service.impl;

import cc.mrbird.common.domain.QueryRequest;
import cc.mrbird.common.service.impl.BaseService;
import cc.mrbird.system.dao.ProblemFeedbackMapper;
import cc.mrbird.system.domain.Daliy;
import cc.mrbird.system.domain.ProblemFeedback;
import cc.mrbird.system.domain.ProjectEntry;
import cc.mrbird.system.service.DaliyService;
import cc.mrbird.system.service.ProblemFeedbackService;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("ProblemFeedbackService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ProblemFeedbackServiceImpl extends BaseService<ProblemFeedback> implements ProblemFeedbackService {

    private static final Integer ONE_DAY = 0;

    @Value("${attach_path}")
    private String attach_path;
    @Value("${attach_drive}")
    private String attach_drive;
    @Value("${attach_remote_url}")
    private String attach_remote_url;


    @Autowired
    private ProblemFeedbackMapper problemFeedbackMapper;

    @Override
    public ProblemFeedback upload(MultipartFile file) throws IOException {
        //附件唯一标识
        String enclosureTag = (String) getDaysBetwwen(ONE_DAY).toArray()[0];
        //文件名
        String filename = file.getOriginalFilename();
        //储存路径
        String savePath = attach_drive + attach_path;
        //文件类型
        String fileType = filename.substring(file.getOriginalFilename().lastIndexOf(".")+1).toLowerCase();

        SaveFileFromInputStream(savePath,file.getInputStream(),enclosureTag+filename);

        ProblemFeedback problemFeedback = new ProblemFeedback();
        problemFeedback.setFileName(filename);
        problemFeedback.setEnclosure(enclosureTag+filename);
        problemFeedback.setEnclosureTag(enclosureTag);
        problemFeedback.setFileType(fileType);
        return problemFeedback;
    }

    @Override
    public List<ProblemFeedback> findAllProblemFeedback(ProblemFeedback problemFeedback, QueryRequest request) {
        return problemFeedbackMapper.selectAll();
    }

    @Override
    public ProblemFeedback findProblemFeedback(Integer id) {
        ProblemFeedback problemFeedback = new ProblemFeedback();
        problemFeedback.setId(id);
        return problemFeedbackMapper.selectOne(problemFeedback);
    }

    @Override
    public Boolean addProblemFeedback(ProblemFeedback problemFeedback) {
        problemFeedback.setCreateTime(new Date());
        problemFeedback.setEnclosureTag("0");
        int insert = problemFeedbackMapper.insert(problemFeedback);
        if (insert>0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateProblemFeedback(ProblemFeedback problemFeedback) {
        int update = problemFeedbackMapper.updateByPrimaryKey(problemFeedback);
        if (update>0) {
            return true;
        }
        return false;
    }

    @Override
    public ProblemFeedback getProblemFeedback(ProblemFeedback problemFeedback) {
        return problemFeedbackMapper.selectOne(problemFeedback);
    }

    @Override
    public void deleteProblemFeedback(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        this.batchDelete(list, "id", ProblemFeedback.class);
    }


    public void SaveFileFromInputStream(String filePath,InputStream stream, String filename) throws IOException {
        FileOutputStream fs=new FileOutputStream( filePath + "/" + filename);
        byte[] buffer = new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread=stream.read(buffer))!=-1){
            bytesum+=byteread;
            fs.write(buffer,0,byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
//        CloseableHttpClient httpClient = null;
//        CloseableHttpResponse response = null;
//        httpClient = HttpClients.createDefault();
//
//        HttpPost httpPost = new HttpPost(baseUrl + "/upload?dir=" + filePath);
//        new InputStreamB

    }


    private static Date getDateAdd(int days){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, -days);
        return c.getTime();
    }

    private static List getDaysBetwwen(int days){
        List dayss = new ArrayList<>();
        Calendar start = Calendar.getInstance();
        start.setTime(getDateAdd(days));
        Long startTIme = start.getTimeInMillis();
        Calendar end = Calendar.getInstance();
        end.setTime(new Date());
        Long endTime = end.getTimeInMillis();
        Long oneDay = 1000 * 60 * 60 * 24l;
        Long time = startTIme;
        while (time <= endTime) {
            Date d = new Date(time);
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            dayss.add(df.format(d));
            time += oneDay;
        }
        return dayss;
    }
}
